package com.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 * 扩展spring默认地区切换拦截器
 * 
 * 2013-8-15 上午10:11:43
 * 
 * @author <a href="xinyuan.guo@baozun.cn">郭馨元</a>
 * 
 */
public class ExtendedLocaleChangeInterceptor extends LocaleChangeInterceptor {

	private String paramName = DEFAULT_PARAM_NAME;


	private List<String> langs;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		String newLocale = null;
		try {
			newLocale = request.getParameter(this.paramName);
		} catch (Exception e) {
//			throw new BusinessException(ShopErrorCodes.ERR_GET_PARAMETER);
			e.printStackTrace();
		}
		if (newLocale != null) {
			if (!langs.isEmpty())
				if (langs.contains(newLocale)) {
					LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
					if (localeResolver == null)
						throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
					localeResolver.setLocale(request, response, StringUtils.parseLocaleString(newLocale));
				}
		}
		return true;
	}

	public List<String> getLangs() {
		return langs;
	}

	public void setLangs(List<String> langs) {
		this.langs = langs;
	}
}
